﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using RentAWorker.DataAccess.Interfaces;
using System.Data.Objects;
using System.Data;
using RentAWorker.DataAccess.Entities;

namespace RentAWorker.DataAccess
{
    public class CustomerDataAccess : ICustomerAccess
    {
        public Customer GetCustomerById(int customerId)
        {
            using (BigDays2009Entities db = new BigDays2009Entities())
            {
                db.Customer.MergeOption = MergeOption.NoTracking;
                return db.Customer.Where(c => c.CustomerID == customerId).FirstOrDefault();
            }
        }

        public Customer GetCustomerByMembershipId(Guid membershipId)
        {
            using (BigDays2009Entities db = new BigDays2009Entities())
            {
                db.Customer.MergeOption = MergeOption.NoTracking;
                return db.Customer.Where(c => c.MembershipID == membershipId).FirstOrDefault();
            }
        }

        public IEnumerable<Customer> GetCustomers(string searchString)
        {
            using (BigDays2009Entities db = new BigDays2009Entities())
            {
                db.Customer.MergeOption = MergeOption.NoTracking;

                    return (from cust in db.Customer
                            where (String.IsNullOrEmpty(searchString) 
                                    || cust.Name.Contains(searchString))
                            select cust).ToList();
            }
        }

        public Customer CreateCustomer(Customer newCustomer)
        {
            using (BigDays2009Entities db = new BigDays2009Entities())
            {
                db.AddToCustomer(newCustomer);
                db.SaveChanges();

                return GetCustomerById(newCustomer.CustomerID);
            }
        }

        public void DeleteCustomer(int customerId)
        {
            using (BigDays2009Entities db = new BigDays2009Entities())
            {
                db.DeleteObject(db.Customer.Where(cust => cust.CustomerID == customerId).First());
                db.SaveChanges();
            }
        }

        public Customer UpdateCustomer(Customer updateCustomer)
        {
            using (BigDays2009Entities db = new BigDays2009Entities())
            {
                Customer original = (Customer)db.GetObjectByKey(updateCustomer.EntityKey);

                db.ApplyPropertyChanges(updateCustomer.EntityKey.EntitySetName, updateCustomer);
                db.SaveChanges();

                return GetCustomerById(updateCustomer.CustomerID);
            }
        }
    }
}
